package com.jayhuang.user_center.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.jayhuang.user_center.common.ErrorCode;
import com.jayhuang.user_center.exception.BusinessException;
import com.jayhuang.user_center.utils.Result;
import com.jayhuang.user_center.contant.UserConstant;
import com.jayhuang.user_center.pojo.User;
import com.jayhuang.user_center.pojo.request.UserLoginRequest;
import com.jayhuang.user_center.pojo.request.UserRegisterRequest;
import com.jayhuang.user_center.pojo.response.SafetUserResponse;
import com.jayhuang.user_center.service.UserService;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;

import static com.jayhuang.user_center.contant.UserConstant.USER_LOGIN_STATE;

/**
 * 用户接口
 * @author jayhuang
 */
@RestController
@RequestMapping("/user")
@CrossOrigin
public class UserController {

    @Resource
    private UserService userService;

    /**
     * @param urr 用户注册信息
     * @return  返回用户id
     */
    @PostMapping("/register")
    public Result userRegister(@RequestBody UserRegisterRequest urr) {
        if (urr == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        String userAccount = urr.getUserAccount();
        String userPassword = urr.getUserPassword();
        String checkPassword = urr.getCheckPassword();
        String planetCode = urr.getPlanetCode();
        if (StringUtils.isBlank(userAccount) || StringUtils.isBlank(userPassword) || StringUtils.isBlank(checkPassword) || StringUtils.isBlank(planetCode)) {
            throw new BusinessException(ErrorCode.NULL_ERROR);
        }
        return userService.userRegister(userAccount, userPassword, checkPassword, planetCode);
    }


    /**
     * @param ulr 用户登录信息
     * @param request 请求对象
     * @return 登录后返回用户信息
     */
    @PostMapping("/login")
    public Result userLogin(@RequestBody UserLoginRequest ulr, HttpServletRequest request) {
        if (ulr == null) {
            throw new BusinessException(400,"账号或密码不能为空","");
        }
        String userAccount = ulr.getUserAccount();
        String userPassword = ulr.getUserPassword();
        if (StringUtils.isBlank(userAccount) || StringUtils.isBlank(userPassword)) {
            throw new BusinessException(ErrorCode.NULL_ERROR,"账号或密码不能为空");
        }
        return Result.success(200, "success",userService.doLogin(userAccount, userPassword, request));
    }


    @PostMapping("/logout")
    public Result logout(HttpServletRequest request) {
        if (request == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"登录不存在");
        }
        userService.userLogout(request);
        return Result.success(200,"success");
    }


    /**
     * 登录态返回用户信息
     * @param request 请求对象
     * @return 返回用户信息
     */
    @GetMapping("/current")
    public Result getCurrentUser(HttpServletRequest request) {
        Object attribute = request.getSession().getAttribute(USER_LOGIN_STATE);
        SafetUserResponse currentUser = (SafetUserResponse) attribute;
        if (currentUser == null) {
            throw new BusinessException(ErrorCode.NO_LOGIN);
        }
        Long userId = currentUser.getId();
        User byId = userService.getById(userId);
        return Result.success(200,"success",getSafetUser(byId));
    }


    /**
     * 获取包含用户名的所有用户
     * @param username 用户名称
     * @param request 请求对象
     * @return 返回查询到的所有用户
     */
    @GetMapping("/search")
    public Result searchUserNames(String username, HttpServletRequest request) {
        /*判断是否是管理员*/
        if (!isAdmin(request)) {
            throw new BusinessException(ErrorCode.NO_AUTH, "不是管理员");
        }
        /*查询用户信息*/
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        if (StringUtils.isNotBlank(username)) {
            queryWrapper.like("username", username);
        }
        List<User> userList = userService.list(queryWrapper);
        List<SafetUserResponse> safetUserResponses = new ArrayList<>();
        userList.forEach(user -> safetUserResponses.add(getSafetUser(user)));
        return Result.success(200,"success",safetUserResponses);
    }

    /**
     * 删除用户
     * @param id 用户id
     * @param request 请求对象
     * @return 返回是否删除成功
     */
    @DeleteMapping("/{id}")
    public Result searchUserNames(@PathVariable Integer id, HttpServletRequest request) {
        if (isAdmin(request)) {
            throw new BusinessException(ErrorCode.NO_AUTH, "不是管理员");
        }
        if (id == null || id <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "id不能为空");
        }
        return Result.success(200,"success",userService.removeById(id));
    }

    /**
     * 是否为管理员
     * @param request
     * @return true or false
     */
    private  boolean isAdmin(HttpServletRequest request) {
        Object userObj = request.getSession().getAttribute(USER_LOGIN_STATE);
        SafetUserResponse user = (SafetUserResponse) userObj;
        return user != null && (user.getUserRole() == UserConstant.ADMIN_ROLE);
    }


    /**
     * 用户信息脱敏
     * @param user 脱敏目标对象
     * @return 脱敏后的对象
     */
    public SafetUserResponse getSafetUser(User user) {
        if (user == null) {
            return null;
        }
        SafetUserResponse safetUserResponse = new SafetUserResponse();
        BeanUtils.copyProperties(user, safetUserResponse);
        return safetUserResponse;
    }
}
